import ReCAPTCHA from 'react-google-recaptcha'
import styles from './index.module.scss'
import { forwardRef, useEffect, useRef } from 'react'
import EventBus from '@/utils/emitter'

const Index = () => {
  const ref = useRef()
  const circleVerifyRef = useRef(null)
  useEffect(() => {
    circleVerifyRef.current = setInterval(async () => {
      // 验证机器人
      const recaptchaValue = ref.current.getValue()
      if (!recaptchaValue) {
        return
      }
      const verRes = await fetch('/api/verify-robot', {
        method: 'POST',
        body: JSON.stringify({ recaptcha: recaptchaValue }),
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const data = await verRes.json()
      if (data.success) {
        EventBus.emit('signRobotSuccess')
        clearInterval(circleVerifyRef.current)
      }
    }, 1000)
    return () => {
      if (circleVerifyRef.current) {
        clearInterval(circleVerifyRef.current)
      }
    }
  }, [])
  return (
    <div className={styles.container}>
      <ReCAPTCHA ref={ref} sitekey="6LfPUMQpAAAAANCFavp1IfctsF4GImwPzj7MuCKO" />
    </div>
  )
}

export default forwardRef(Index)
